package org.wmq.shopmanager.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.wmq.shopmanager.service.OrderService;
import org.wmq.shopmanager.service.OrderStatisticService;
import org.wmq.shopmodel.Entity.product.Order;
import org.wmq.shopmodel.Entity.product.OrderStatistic;

import java.math.BigDecimal;
import java.time.LocalDate;

@Component
@RequiredArgsConstructor
public class OrderStatisticTask {
    private final OrderService orderService;
    private final OrderStatisticService orderStatisticService;

    @Scheduled(cron = "0 0 2 * * ?")
    public void orderTotalAmountStatistic(){
        LocalDate date = LocalDate.now().minusDays(1L);
        BigDecimal totalAmount = this.orderService.getTotalAmountByDate(date);
        if (totalAmount == null || totalAmount.equals(BigDecimal.ZERO)){
            return;
        }
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCreateTime,date);
        long count = this.orderService.count(queryWrapper);
        OrderStatistic orderStatistic = new OrderStatistic();
        orderStatistic.setOrderDate(date);
        orderStatistic.setTotalAmount(totalAmount);
        orderStatistic.setOrderCount(count);
        this.orderStatisticService.save(orderStatistic);
    }
}
